<?php

namespace app\web\logic;

use app\common\component\Redis;

/**
 * 通用逻辑类
 * Class CommonLogic
 * @package app\web\logic
 */
class CommonLogic
{
    /**
     * 将ip转为10进制
     * @param $ip
     * @return float|int|string
     */
    private static function ipToLong($ip)
    {
        $ip = explode('.', $ip);
        $ip = array_reverse($ip);//数组反转
        $r = 0;
        for($i=0,$j=count($ip); $i<$j; $i++){
            $r += $ip[$i] * pow(256, $i);
        }
        $r = sprintf("%u", $r);
        return $r;
    }

    /**
     * 生成随机数字
     * @param $controller
     * @param $action
     * @param $ip
     * @return string
     */
    public static function createNoncestr($controller, $action)
    {
        $ipLong = self::ipToLong($_SERVER['REMOTE_ADDR']);
        $randNum = rand(10, 99);
        $value = sprintf('%s_%s_%s_%d', $controller, $action, $ipLong, $randNum);
        $key = Redis::getInstance()->getRedisName(Redis::ACCESS_NONCESTR_PREFIX, $value);
        $value = md5($value);
        Redis::getInstance()->setex($key, 1800, $value);
        return $key . $randNum;
    }


}